package com.example.redpacket.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description
 * @Author 大雄 <1194353393@qq.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/5/1 12:45
 */
public class RedPacketUtil {
    /**
     * 发红包算法，金额参数以分为单位
     *
     * @param totalAmount    总金额
     * @param totalPeopleNum 总人数
     * @return 随机金额列表
     */
    public static List<Integer> divideRedPackage(Integer totalAmount, Integer totalPeopleNum) {
        List<Integer> amountList = new ArrayList<>();

        if (totalAmount > 0 && totalPeopleNum > 0) {
            int restAmount = totalAmount;
            int restPeopleNum = totalPeopleNum;

            Random random = new Random();
            for (int i = 0; i < totalPeopleNum - 1; i++) {
                // 随机范围：[1，剩余人均金额的两倍)，左闭右开

                int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
                restAmount -= amount;
                restPeopleNum--;
                amountList.add(amount);
            }
            amountList.add(restAmount);
        }

        return amountList;
    }
}
